import Vue from "vue";
import VueRouter from "vue-router";
import LoginView from "@/views/login-view";
import MainView from "@/views/main-view";

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject)
        return originalPush.call(this, location, onResolve, onReject);
    return originalPush.call(this, location).catch((err) => err);
};

Vue.use(VueRouter);

const routes = [
    {
        path:'/',
        redirect: '/index'
    },
    {
        path:'/index',
        component:MainView,
        meta:{
            requiresAuth: true
        }
    },
    {
        path:'/login',
        name:'LoginView',
        component:LoginView,
        meta:{
            requiresAuth: false
        }
    }
]

const router = new VueRouter({
    routes
})

//路由拦截
router.beforeEach((to,from,next)=>{
    const toPath = to.path;
    const fromPath = from.path;
    const token = localStorage.getItem('token');
    const app = router.app;
    const requiresAuth = to.meta.requiresAuth;
    //未登录时，跳转到登录页面，登录成功后，再次跳转到重定向页面
    if(requiresAuth){
        if(!token){
            next('/login?redirectUrl='+fromPath);
        }else{
            next();
        }
    }else{
        next();
    }
});

export default router;